import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import BackButton from '../components/BackButton';
import { format } from 'date-fns';

interface Transaction {
  id: string;
  trans_code: string;
  trans_sn: string;
  rrn: string;
  orderid: string;
  pan: string;
  trans_amt: string;
  trans_date: string;
  trans_time: string;
  merno: string;
  terminal: string;
  resp_code: string;
  bank_date: string;
  created_at: string;
  pay_order: string;
}

interface PaginationInfo {
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

const TransactionList: React.FC = () => {
  const navigate = useNavigate();
  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchPan, setSearchPan] = useState('');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [transType, setTransType] = useState('');
  const [pagination, setPagination] = useState<PaginationInfo>({
    total: 0,
    page: 1,
    pageSize: 20,
    totalPages: 0
  });

  const transTypeOptions = [
    { value: '', label: '全部' },
    { value: 'CEP', label: '消费' },
    { value: 'CEF', label: '退货' }
  ];

  const fetchTransactions = async () => {
    try {
      setLoading(true);
      setError(null);
      
      const params: any = {
        page: pagination.page,
        page_size: pagination.pageSize
      };

      if (searchPan) params.pan = searchPan;
      if (startDate) params.start_date = startDate.replace(/-/g, '');
      if (endDate) params.end_date = endDate.replace(/-/g, '');
      if (transType) params.trans_code = transType;

      const response = await axios.get('/api/transactions', { params });
      
      setTransactions(response.data);
      setPagination({
        total: parseInt(response.headers['x-total-count'] || '0'),
        page: parseInt(response.headers['x-page'] || '1'),
        pageSize: parseInt(response.headers['x-page-size'] || '20'),
        totalPages: parseInt(response.headers['x-total-pages'] || '0')
      });
    } catch (err) {
      setError('获取交易记录失败');
      console.error('Error fetching transactions:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTransactions();
  }, [pagination.page, pagination.pageSize]);

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setPagination(prev => ({ ...prev, page: 1 }));
    fetchTransactions();
  };

  const handlePageChange = (newPage: number) => {
    setPagination(prev => ({ ...prev, page: newPage }));
  };

  const formatAmount = (amount: string) => {
    const num = parseInt(amount);
    return (num / 100).toFixed(2);
  };

  const getTransactionTypeText = (type: string) => {
    const typeMap: { [key: string]: string } = {
      'CEP': '消费',
      'CEF': '退货'
    };
    return typeMap[type] || type;
  };

  const formatDateTime = (date: string, time: string) => {
    return `${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6, 8)} ${time.slice(0, 2)}:${time.slice(2, 4)}:${time.slice(4, 6)}`;
  };

  const handleRefund = (transaction: Transaction) => {
    navigate('/cef', { state: { originalTransaction: transaction } });
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-violet-50 via-indigo-50 to-purple-50 py-8 px-4">
      <div className="max-w-7xl mx-auto">
        <BackButton />
        
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-white/80 backdrop-blur-lg rounded-2xl shadow-xl p-8 mt-4 border border-white/20"
        >
          <h1 className="text-3xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-violet-600 to-indigo-600 mb-8">交易历史记录</h1>

          {/* 搜索表单 */}
          <form onSubmit={handleSearch} className="mb-8 grid grid-cols-1 md:grid-cols-4 gap-6">
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700">卡号</label>
              <input
                type="text"
                value={searchPan}
                onChange={(e) => setSearchPan(e.target.value)}
                placeholder="输入卡号搜索"
                className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:ring-2 focus:ring-violet-500 focus:border-transparent transition-all duration-200"
              />
            </div>
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700">开始日期</label>
              <input
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:ring-2 focus:ring-violet-500 focus:border-transparent transition-all duration-200"
              />
            </div>
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700">结束日期</label>
              <input
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:ring-2 focus:ring-violet-500 focus:border-transparent transition-all duration-200"
              />
            </div>
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700">交易类型</label>
              <select
                value={transType}
                onChange={(e) => setTransType(e.target.value)}
                className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:ring-2 focus:ring-violet-500 focus:border-transparent transition-all duration-200"
              >
                {transTypeOptions.map(option => (
                  <option key={option.value} value={option.value}>{option.label}</option>
                ))}
              </select>
            </div>
            <div className="md:col-span-4">
              <button
                type="submit"
                className="w-full md:w-auto px-8 py-2.5 bg-gradient-to-r from-violet-600 to-indigo-600 text-white rounded-xl hover:from-violet-700 hover:to-indigo-700 focus:outline-none focus:ring-2 focus:ring-violet-500 focus:ring-offset-2 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-violet-500/20"
                disabled={loading}
              >
                {loading ? '搜索中...' : '搜索'}
              </button>
            </div>
          </form>

          {/* 错误提示 */}
          {error && (
            <div className="mb-6 p-4 bg-red-50 border border-red-100 rounded-xl">
              <p className="text-red-600">{error}</p>
            </div>
          )}

          {/* 交易列表 - 卡片式布局 */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {transactions.map((transaction) => (
              <motion.div
                key={transaction.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="bg-white/90 backdrop-blur-sm rounded-xl p-6 shadow-lg border border-white/50 hover:shadow-xl transition-all duration-300"
              >
                <div className="flex items-center justify-between mb-4">
                  <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${
                    transaction.trans_code === 'CEP' 
                      ? 'bg-violet-100 text-violet-800' 
                      : 'bg-indigo-100 text-indigo-800'
                  }`}>
                    {getTransactionTypeText(transaction.trans_code)}
                  </span>
                  <span className={`text-lg font-semibold ${
                    transaction.trans_code === 'CEP' 
                      ? 'text-red-600' 
                      : 'text-green-600'
                  }`}>
                    {transaction.trans_code === 'CEP' ? '-' : '+'}¥{formatAmount(transaction.trans_amt)}
                  </span>
                </div>
                <div className="text-sm text-gray-500 mb-3">
                  {formatDateTime(transaction.trans_date, transaction.trans_time)}
                </div>
                
                {/* 为消费交易添加退货按钮 */}
                {transaction.trans_code === 'CEP' && (
                  <div className="mt-4 pt-3 border-t border-gray-100">
                    <button
                      onClick={() => handleRefund(transaction)}
                      className="w-full py-2 px-4 bg-gradient-to-r from-indigo-500 to-violet-500 text-white text-sm rounded-lg hover:from-indigo-600 hover:to-violet-600 transition-all duration-200 flex items-center justify-center"
                    >
                      <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6" />
                      </svg>
                      退货
                    </button>
                  </div>
                )}
              </motion.div>
            ))}
            {transactions.length === 0 && !loading && (
              <div className="col-span-full text-center py-12 text-gray-500">
                暂无交易记录
              </div>
            )}
          </div>

          {/* 分页控件 */}
          {pagination.totalPages > 1 && (
            <div className="mt-8 flex justify-between items-center">
              <div className="text-sm text-gray-700">
                共 {pagination.total} 条记录，第 {pagination.page} / {pagination.totalPages} 页
              </div>
              <div className="flex space-x-2">
                <button
                  onClick={() => handlePageChange(pagination.page - 1)}
                  disabled={pagination.page === 1}
                  className="px-4 py-2 rounded-xl border border-gray-200 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
                >
                  上一页
                </button>
                <button
                  onClick={() => handlePageChange(pagination.page + 1)}
                  disabled={pagination.page === pagination.totalPages}
                  className="px-4 py-2 rounded-xl border border-gray-200 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
                >
                  下一页
                </button>
              </div>
            </div>
          )}
        </motion.div>
      </div>
    </div>
  );
};

export default TransactionList; 